package com.kaoyaya.util;

import java.io.StringReader;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

/**
 * XML工具类
 * @author Goven
 * @date 2012-12-14
 */
public class XmlUtil {
	
	private static XmlPullParserFactory factory;
	
	/**
	 * 获得XmlPullParserFactory对象
	 * @return XmlPullParserFactory对象
	 */
	private static XmlPullParserFactory getXmlPullParserFactory() throws Exception{
		if(factory == null){
			synchronized (XmlUtil.class) {
				factory = XmlPullParserFactory.newInstance();
			}
		}
		return factory;
	}
	
	/**
	 * 解析XML,获取JSON数据部分,如果没有包含XML标签，则直接返回
	 * @param xml XML格式数据
	 * @return JSON格式数据
	 */
	public static String getJson(String xml) {
		if (StringUtil.isNotTrimBlank(xml) && xml.startsWith("<") && xml.endsWith(">")) {
			try {
				XmlPullParser parser = getXmlPullParserFactory().newPullParser();
				parser.setInput(new StringReader(xml));
				parser.next();
				xml = parser.nextText();
			} catch (Exception e) {
				return null;
			}
		}
		return xml;
	}
}
